package de.baumann.browser.activitys.hash

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.SeekBar
import android.widget.Toast
import de.baumann.browser.BuildConfig
import de.baumann.browser.R
import de.baumann.browser.activitys.center.TurnVipActivity
import de.baumann.browser.activitys.user.BindETHActivity
import de.baumann.browser.base.BaseOdinActivity
import de.baumann.browser.db.ETHWallet
import de.baumann.browser.iview.IWalletBalanceView
import de.baumann.browser.present.WalletBalancePresenter
import de.baumann.browser.utils.*
import de.baumann.browser.utils.web3j.WalletDaoUtils
import de.baumann.browser.views.dialog.BindEthDialog
import de.baumann.browser.views.dialog.LicenceNotActiveDialog
import de.baumann.browser.views.dialog.PayPwdDialog
import kotlinx.android.synthetic.main.activity_buy_hash.*
import kotlinx.android.synthetic.main.include_tool_bar.*
import org.web3j.crypto.Credentials
import org.web3j.crypto.WalletUtils
import java.io.File
import java.math.BigDecimal

/**
 * @author:
 * @date:2018/12/13 9:58
 * @discription: 购买算力包
 */
class BuyHashActivity : BaseOdinActivity<IWalletBalanceView, WalletBalancePresenter>(), IWalletBalanceView {

    override fun getTitleText(): String {
        return getString(R.string.buy_hash)
    }

    override fun getLayout(): Int {
        return R.layout.activity_buy_hash
    }

    private var password = ""
    override fun initView() {
        initToolbar(commToolBar, commTitle)

        edHashNum.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(p0: Editable?) {
                if (edHashNum.text.isEmpty()) {
                    bhsb.progress = 0
                } else {
                    val num = edHashNum.text.toString().toInt()
                    bhsb.progress = num
                }
            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }
        })

        bhsb.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(p0: SeekBar?, p1: Int, p2: Boolean) {
                edHashNum.setText(p0?.progress.toString())
                tvBHBB.text = "${p0?.progress.toString()} 算力"
                if (p0!!.progress == 0) {
                    tvBHODINB.text = "0 ODIN"
                } else {
                    tvBHODINB.text = "${BigDecimal(p0!!.progress).multiply(BigDecimal(6.4)).setScale(4, BigDecimal.ROUND_DOWN)} ODIN"
                }
                edHashNum.setSelection(edHashNum.text.length)
            }

            override fun onStartTrackingTouch(p0: SeekBar?) {
            }

            override fun onStopTrackingTouch(p0: SeekBar?) {
            }
        })

        btnBuyHash.setOnClickListener {

            //licence 判断
//            val licenceStatus = getLicenceStatus()
//            if (licenceStatus != Constants.LICENCE_AVAILABLE) {
//                LicenceNotActiveDialog(mContext, View.OnClickListener {
//                    TurnVipActivity.startTurnVipActivity(mContext)
//                }).show()
//                return@setOnClickListener
//            }

            val num = edHashNum.text.toString().trim()
            if (num.isEmpty() || num == "0") {
                showShortToast("请输入算力包数量")
                return@setOnClickListener
            }
            if (BigDecimal(num) > maxHash) {
                showShortToast("余额不足")
                return@setOnClickListener
            }


            pwdd = PayPwdDialog(mContext, object : PayPwdDialog.PwdCallback {
                override fun callback(pwd: String) {
                    password = pwd
                    showLoading()
                    if (getPrivateKey().isEmpty()) {
                        hideLoading()
                        return
                    }
                    presenter.transfer()
                    pwdd!!.dismiss()
                }
            })
            pwdd!!.show()
        }
    }

    private var pwdd: PayPwdDialog? = null

    override fun initData() {
        presenter.getWalletBalance()
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_hash_record, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        HashValueActivity.startHashValueActivity(mContext)
        return super.onOptionsItemSelected(item)
    }

    private fun getWallet(): ETHWallet {
        return intent.getSerializableExtra("wallet") as ETHWallet
    }


    override fun getAddress(): String {
        return getFromAddress()
    }

    private var balance = ""
    override fun setBalance(balance: String) {
        this.balance = balance
        tvBHOB.text = "可用 $balance ODIN"
        if (balance.isNotEmpty()) {
            calculateMaxHash()
        }
    }

    override fun getFromAddress(): String {
        return getWallet().getAddress()
    }

    private var maxHash: BigDecimal = BigDecimal(0)
    private fun calculateMaxHash() {
        val odin = BigDecimal(balance)
        val scale = BigDecimal(6.4).setScale(4, BigDecimal.ROUND_DOWN)
        maxHash = odin.divide(scale).setScale(4, BigDecimal.ROUND_DOWN)
        bhsb.max = maxHash.toInt()
        tvMaxHash.text = "${maxHash.toInt()} 算力"
    }


    override fun getPrivateKey(): String {
        if (getCredentials() == null) {
            return ""
        }
        return getCredentials()!!.ecKeyPair.privateKey.toString(16)
    }

    private fun getCredentials(): Credentials? {
        try {
            return WalletUtils.loadCredentials(password, File(getWallet().keystorePath))
        } catch (e: Exception) {
            if ("Invalid password provided" == e.message) {
                Toast.makeText(mContext, "密码错误", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(mContext, e.message, Toast.LENGTH_SHORT).show()
            }
        }
        return null
    }

    override fun getToAddress(): String {
        return BuildConfig.BUY_HASH_ADDRESS
    }

    override fun getAmount(): String {
        val amountStr = edHashNum.text.toString().trim()
        if (amountStr.isEmpty()) {
            return ""
        }
        val amount = BigDecimal(amountStr)
        val scale = BigDecimal(6.4)
        return amount.multiply(scale).setScale(4, BigDecimal.ROUND_DOWN).toString()
    }

    override fun getFee(): String {
        return ""
    }

    override fun transferSuccess(hash: String) {
        hideLoading()
        showShortToast("交易已发送，正在处理")
        finish()
    }

    override fun createPresenter(): WalletBalancePresenter {
        return WalletBalancePresenter()
    }

    override fun createView(): IWalletBalanceView {
        return this
    }

    companion object {
        fun startBuyHashActivity(context: Context) {
//            var bindEth: String = WalletDaoUtils.getCurrent().address
            var bindEth: String? = getMoneyAddress()
//            var bindEth = getUser()?.eth_address
//            var bindEth = WalletDaoUtils.getCurrent().address
            Log.d("lwq", "startBuyHashActivity:=== $bindEth")
            Log.d("lwq", "startBuyHashActivity:=== ${WalletDaoUtils.getCurrent().address}")

            if (bindEth?.startsWith("0x") == true) {
                bindEth = "odx" + bindEth.substring(2)
            }
            if (bindEth == null) {
                BindEthDialog(context, View.OnClickListener {
                    BindETHActivity.startBindETHActivity(context, "")
                }).show()
                return
            }

            if (bindEth.startsWith("odx")) {
                bindEth = "0${bindEth.substring(2)}"
            }
            Log.d("lwq", "startBuyHashActivity:111=== $bindEth")
            val ethWallet = WalletDaoUtils.queryWalletByAddress(bindEth)

            if (ethWallet == null) {
                Toast.makeText(context, "请导入绑定地址所对应的钱包", Toast.LENGTH_SHORT).show()
                return
            }
            //licence 判断
//            val licenceStatus = getLicenceStatus()
//            if (licenceStatus != Constants.LICENCE_AVAILABLE) {
//                LicenceNotActiveDialog(context, View.OnClickListener {
//                    TurnVipActivity.startTurnVipActivity(context)
//                }).show()
//                return
//            }

            context.startActivity(Intent(context, BuyHashActivity::class.java).apply {
                val bundle = Bundle().apply {
                    putSerializable("wallet", ethWallet)
                }
                putExtras(bundle)
            })
        }
    }

    override fun getLimit(): Long {
        return 80000
    }
}
